<template>
  <!-- 课程内页 -->
  <div class="item-course-container">
    <div class="course-video">
      <!-- 小程序 -->
      <div class="course-video-box poster-wrap" v-if="!showBuy && have_remaining_flowget==1">
        <img :src="poster" alt="" class="poster-img">
        <div class="over-bg video-box">
          <video
            id="wx-course-video"
            v-if="!showBuy && have_remaining_flowget==1"
            ref="videoPlay"
            class="course-video-con"
            @play="videoPlay"
            @pause="videoPause"
            @loadedmetadata="videoLoadedmetadata"
            @timeupdate="videoTimeupdate"
            @error="videoError"
            playsinline="isiPhoneShowPlaysinline"
            x5-video-player-type="h5-page"
            t7-video-player-type="inline"
            webkit-playsinline="isiPhoneShowPlaysinline"
            x-webkit-airplay=""
            controls="controls"
            data-role="txp_video_tag"
            :show-casting-button="showButton"
            :src="course.video_url"></video>
        </div>
        <div class="video-play">
          <div class="icon" @click="clickVideoPlay"></div>
        </div>
      </div>
      <div class="poster-wrap" v-if="showBuy">
        <img :src="poster" alt="" class="poster-img">
        <div class="over-bg">
          <div class="icon"></div>
          <div class="txt">当前内容购买专栏后才能收看</div>
        </div>
      </div>
      <!-- 已购买，但流量不足 -->
      <div class="poster-wrap" v-if="!showBuy && !have_remaining_flowget">
        <img :src="poster" alt="" class="poster-img">
        <div class="over-bg">
          <div class="icon"></div>
          <div class="txt">流量不足，请联系商家</div>
        </div>
      </div>
    </div>
    <div class="course-info item-block">
      <div class="price-wrap" v-if="showBuy">
        <div class="price-info">
          <div class="price" v-html="scaleGoodsPriceFn(course_column_info.price)"></div>
          <div class="commision" v-if="course_column_info.commission>0">
            <span>{{course_column_info.earn_alias}}</span><span>¥{{course_column_info.commission}}</span>
          </div>
        </div>
        <div class="other-price" v-if="course_column_info.is_display_original_price==1">
          <i>原价:</i>
          <span class="original-price">{{course_column_info.original_price}}</span>
        </div>
      </div>
      
      <div class="course-title">{{course.title}}</div>
      <div class="play-num">{{course.play_num}}次学习</div>
    </div>
    <div class="course-list item-block">
      <div class="item" @click="linkTo(course_column_info.link)">
        <div class="item-img">
          <img :src="course_column_info.img_path+'w640'" alt="" v-if="course_column_info.is_compress==1">
          <img :src="course_column_info.img_path" alt="" v-else>
        </div>
        <div class="item-con">
          <div class="title">{{course_column_info.title}}</div>
          <div class="bottom-con">
            <div class="num">共{{course_column_info.column_num}}节课</div>
            <van-button class="more-btn" plain hairline round>查看专栏</van-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 详情 -->
    <section class="detail_logo block_logo">
      <span class="liner_detail"></span>
      <span class="detail_content">详情</span>
      <span class="liner_detail"></span>
    </section>
    <section class="mdetail_goodsdet content_detail" :class="[course_column_info.is_item_detail_blank == 1 ?'content_detail_padding':'']">
      <section class="mdetail_goodsdet_con">
        <van-list v-model="loading"
                :finished="finished"
                :error.sync="error"
                :immediate-check="false"
                error-text="请求失败，点击重新加载"
                finished-text=""
                @load="onLoad">
          <diy-tpl :tplData="tplData"></diy-tpl>
        </van-list>
      </section>
    </section>
    <!-- 详情end -->
    <!-- 付费且没有购买过 v-if="course.is_free!=1 && course_column_info.course_brought_before!=1"-->
    <div class="bottom-fixed" v-if="showBuy">
      <fixed-button :detailAll="course_column_info" :itemCourse="true" v-if="true" />
    </div>

    <!-- 授权弹出框 -->
    <small-login ref="smalllogin"></small-login>
  </div>
</template>

<script>
  import diyTpl from '@/components/diyTpl/index'
  import { scaleGoodsPrice } from '@/utils/index'
  import { coursePages, GetWatchTime, newItemDetailDiyHtml } from '@/api/item/item'
  import fixedButton from './../itemDetail//detailWrapper/fixedButton'
  import Storage from '@/utils/store.js'
  import { openPage,mpShare } from '@/utils/utils'
  import small from '@/smallapp/small'
  import Vue from 'vue'
  export default Vue.extend({
    name: 'index',
    components: {
      diyTpl,
      fixedButton
    },
    data() {
      return {
        isMiniprogram: process.env.isMiniprogram,
        course_id: '',
        course: {},
        course_column_info: {},
        showBuy: false,
        have_remaining_flowget: 1, // 是否有剩余流量 1有 0没有
        loading: false,
        error: false,
        finished: false,
        listParams: {
          p: 1,
          item_id: ''
        },
        tplData: [],
        poster: '',
        iframe_str: '',
        player: null,
        fileID: '',
        appID: '',
        duration: 0,
        current_time: 0,
        showButton: false, // 投屏按钮
        videoStatus: 'paused'
      }
    },
    methods: {
      // 点击查看专栏，保存观看记录
      linkTo(url) {
        this.saveVideoInfo(() => {
          // TODO 小程序跳转处理
            openPage(url)
        })
      },
      init() {
        const res = wx.getSystemInfoSync()
        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 50000)
        coursePages({ course_id: this.course_id, item_id: this.listParams.item_id }).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            const resData = res.data
            this.course = resData.course
            this.course_column_info = resData.course_column_info
            this.poster = resData.course.video_cover_url
            this.have_remaining_flowget = resData.course.have_remaining_flowget
            this.current_time = resData.course.current_time || 0 //上次播放记录时间

            // 分享给朋友
            const option = {
              title: resData.jsapi_title,
              imgUrl: resData.jsapi_img,
              shareParam: res.data.jsapi_url.split('?')[1]
            }
            mpShare (true, false, '/goods/pages/itemCourse/index', option)
              wx.setNavigationBarTitle({
                title: resData.course.title || '课程详情'
              })

            this.fileID = resData.course.file_id
            this.appID = resData.course.app_id
            if (this.course.is_free != 1 && this.course_column_info.course_brought_before != 1) {
              this.showBuy = true
              return false
            } else {
              this.showBuy = false
            }
            if (this.have_remaining_flowget != 1) {
              return false
            }

            //小程序中不使用腾讯云点播播放器
            if(this.isMiniprogram){
              return false
            }
            this.$nextTick(() => {
              this.player = new window.TCPlayer('player-container-id', { // player-container-id 为播放器容器 ID，必须与 html 中一致
                fileID: this.fileID, // 请传入需要播放的视频 filID（必须） 5285890799710670616
                appID: this.appID, // 请传入点播账号的 appID（必须） 1400329073
                plugins: {
                  ContinuePlay: { // 开启续播功能
                    auto: true, // [可选] 是否在视频播放后自动续播
                    text: '上次播放至 ', // [可选] 提示文案
                    btnText: '恢复播放' // [可选] 按钮文案
                  }
                }
              })
              this.player.on('loadedmetadata', (res) => {
                this.duration = this.player.duration()
                const width = this.player.videoWidth()
                const height = this.player.videoHeight()
                const containerW = document.querySelector('.item-course-container').offsetWidth
                const obj = document.querySelector('.course-video-con')
                const newH = height / width * containerW
                obj.style.width = containerW + 'px'
                obj.style.height = newH + 'px'
              })
              this.player.on('error', (res) => {
                // console.log('播放器错误码', res)
              })
            })
          } else {
            this.$Error(res.msg)
          }
        })
      },
      // 保存当前播放课程和时长
      saveVideoInfo(callback) {
          // this.current_time = Storage.fetchLocal('tcplayer-lpt-' + this.fileID)
        const params = {
          course_id: this.course_id,
          course_column_id: this.course_column_info.course_column_id,
          duration: this.duration,
          current_time: this.current_time || 0
        }
        GetWatchTime(params).then(res => {
          if (callback) {
            callback()
          }
        })
      },
      scaleGoodsPriceFn(price, className) {
        return scaleGoodsPrice(price, className)
      },
      // 商品详情加载更多
      onLoad() {
        // 商品详情装修数据新版
        newItemDetailDiyHtml(this.listParams).then(res => {
          this.showButton = small.wxCache('isProjectionScreen') // 投屏按钮
          if (res.status == 1) {
            this.loading = false
            const data = res.data
            if (data._diyHtml.length > 0) {
              this.tplData = this.tplData.concat(data._diyHtml)
              this.listParams.p++
              //自动加载下一页
              this.onLoad()
            } else {
              this.finished = true
            }
          } else {
            this.$Error(res.msg)
          }
        })
      },

      /*  小程序播放视频 start */
      //视频元数据加载完成时触发
      videoLoadedmetadata(e){
        this.duration=e.detail.duration
      },
      //播放进度变化时触发时
      videoTimeupdate(e){
        this.current_time=e.detail.currentTime
      },
      videoPlay() {
        this.videoStatus = 'play'
      },
      videoPause() {
        this.videoStatus = 'paused'
      },
      videoError() {
        this.videoStatus = 'paused'
        this.clickVideoPlay()
      },
      // video播放
      clickVideoPlay() {
          const videoPlay = this.$refs.videoPlay[0]
          // // console.log(this.videoStatus, 'videoStatus')
          document.querySelector('.course-video-con').$$getContext().then(context => {
            if (this.videoStatus == 'paused') {
              let curTime = this.current_time
              if (curTime >= this.duration){
                curTime = 0
              }
              context.seek(parseFloat(curTime))
              document.getElementsByClassName('video-box')[0].style.display = 'block'
              document.getElementsByClassName('video-play')[0].style.display = 'none'
              this.videoStatus = 'play'
              context.play()
            } else {
              document.getElementsByClassName('video-play')[0].style.display = 'none'
              this.videoStatus = 'paused'
              context.pause()
            }
          })
      },
      /*  小程序播放视频 end */
    },
    mounted() {
      window.addEventListener('beforeunload', () => {
        this.saveVideoInfo(() => {
          // window.location.href = url
        })
      })

      window.addEventListener('wxshow', () => {
        small.HandleShareParams()
        if (!small.checkLogin()) {
          this.$refs.smalllogin.openSmallLoginPop()
        }
			})
			window.$$subscribe('loginReload', reload => {
        if (reload) {
          this.course_id = this.$route.query.id
          this.listParams.item_id = this.$route.query.item_id || this.$route.query.itemId
          this.init()
          this.onLoad()
        }
			})
    },
    destroyed() { // 页面销毁，同时也销毁video.js对象
      this.saveVideoInfo(() => {
        // window.location.href = url
      })
      if (this.player) {
        this.player.dispose()
      }
    },
    created() {
      this.course_id = this.$route.query.id
      this.listParams.item_id = this.$route.query.item_id || this.$route.query.itemId
      this.init()
      this.onLoad()
    }
  })
</script>
<style lang="scss">
.item-course-container{
  .tcp-skin{
    .vjs-big-play-button{
      width:116px;
      height:116px;
      .vjs-button-icon{
        width:116px;
        height:116px;
        background: url("https://img.wifenxiao.com/h5-wfx/images/item/detail/icon_play.png") no-repeat;
        background-size:100% 100%;
        svg{
          display:none;
        }
      }
    }
  }
}
</style>
<style lang="scss">
@import "src/styles/mixin";
.item-course-container{
  .course-video{
    .course-video-con{
      width:100%;
    }
    .poster-wrap{
      position: relative;
      min-height:340px;
      .poster-img{
        width:100%;
      }
      .over-bg{
        position:absolute;
        top:0;
        left:0;
        width:100%;
        height:100%;
        background:rgba(0,0,0,.6);
        .icon{
          position:absolute;
          top:0;
          left:0;
          right:0;
          bottom:0;
          margin:auto;
          width:116px;
          height:116px;
          background: url("https://img.wifenxiao.com/h5-wfx/images/item/detail/icon_lock.png") no-repeat;
          background-size:100% 100%;
        }
        .txt{
          position:absolute;
          top:50%;
          left:0;
          width:100%;
          margin-top:106px;
          line-height:34px;
          font-size:26px;
          text-align:center;
          color:#fff;
        }
      }
      &.course-video-box{
        .video-play{
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          cursor: pointer;
          .icon{
            position:absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
            margin:auto;
            width:116px;
            height:116px;
            background: url("https://img.wifenxiao.com/h5-wfx/images/item/detail/icon_play.png") no-repeat;
            background-size:100% 100%;
          }
        }
        .video-box{
          display:none;
          position:absolute;
          width:100%;
          height:100%;
          top:0;
          left:0;
          background:#000;
          video{
            position:absolute;
            left:0;
            width:100%;
            height:100%;
            top: 50%;
            -webkit-transform: translateY(-50%);
            transform: translateY(-50%);
          }
        }
      }
    }
  }
  .item-block{
    margin-bottom:20px;
    padding:24px;
    border-radius:20px;
    background:#fff;
    &.course-info{
      border-radius:0 0 20px 20px;
    }
  }
  .price-info{
    display:flex;
    align-items: center;
    .price{
      margin:0 12px 10px 0;
      color:#F30C23;
    }
    .commision{
      color:#94734D;
    }
  }
  .other-price{
    padding:10px 0 20px;
    color:#999;
  }
  .course-title{
    margin:10px 0 28px;
    @include lineClamp(28px,36px,2);
    font-weight:bold;
  }
  .play-num{
    margin-bottom:20px;
    line-height:30px;
    color:#999;
  }
  .item{
    display:flex;
    .item-img{
      overflow:hidden;
      width:200px;
      height:116px;
      border-radius: 6px;
      img{
        display:block;
        width:100%;
      }
    }
    .item-con{
      flex:1;
      display:flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left:20px;
      .title{
        @include lineClamp(26px,34px,2);
      }
    }
    .bottom-con{
      display:flex;
      justify-content: space-between;
      align-items:center;
      .num{
        color:#999;
      }
      .more-btn{
        height:42px;
        padding:0 20px;
        font-size:20px;
        border-color:#F21328;
        color:#F21328;
      }
    }
  }
  //详情等标题
  .block_logo{
    font-size: 28px;
    text-align: center;
    padding: 30px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    .detail_content{
      padding:0 30px;
    }
    .liner_detail{
      height: 2px;
      width: 165px;
      background: #E6E6E6;
      position: relative;
      &::after{
        content: '';
        position: absolute;
        background:#E6E6E6 ;
        width: 8px;
        height: 8px;
        top: 0;
        transform: rotate(-45deg) translateY(-50%);
      }
      &:first-child{
        &::after{
          right: -3px;
        }
      }
      &:last-child{
        &::after{
          left: 3px;
        }
      }
    }
  }
  .content_detail {
    background-color: #fff;
    &.content_detail_padding{
      padding: 0 20px;
    }
  }
}
</style>
